package b.acct.impl

import akka.Done
import b.acct.api._
import b.utils.entity.ACPersistentEntity

/**
  * 贲国称 于 16/12/9 创建。
  */
class C账户PersistentEntity extends ACPersistentEntity with T转账TCC {

  case class CC账户State(
                        v账户: Option[CC账户] = None,
                        v余额资源s: Map[Long, BigDecimal] = Map.empty[Long, BigDecimal]) {
    def f预留余额(v事务ID: Long, v金额: BigDecimal): CC账户State = {
      CC账户State(v账户, v余额资源s.updated(v事务ID, v金额))
    }
    def f更新余额(v事务ID: Long, v新余额: BigDecimal): CC账户State = {
      CC账户State(v账户.map(_.f余额变动(v新余额)), v余额资源s - v事务ID)
    }
    def f恢复余额(v事务ID: Long): CC账户State = {
      CC账户State(v账户, v余额资源s - v事务ID)
    }
  }

  override type Command = T账户Command
  override type Event = T账户Event
  override type State = CC账户State

  override def initialState: CC账户State = CC账户State()

  override def behavior: Behavior = {
    case CC账户State(None, _) => notCreated.orElse(getCommand)
    case CC账户State(Some(_), _) => transfer.orElse(getCommand)
  }

  def f账号(state: State): String = state.v账户.get.v账号
  def f余额(state: State): BigDecimal = state.v账户.get.v余额

  private val getCommand = Actions()
    .onReadOnlyCommand[CC账户GetCommand, Option[CC账户]] {
      case (CC账户GetCommand(), ctx, state) => ctx.reply(state.v账户)
    }

  private val notCreated = Actions()
    .onCommand[CC开户Command, Done](f开户)
    .onEvent {
      case (event: CC新账户Event, _) => CC账户State(Some(event.v账户))
    }

  private[this] def f开户: TypePersistDone = {
    case (cmd: CC开户Command, ctx, _) => persistDone(CC新账户Event(CC账户(cmd.v账号)))(ctx)
  }

}
